<template>
  <el-card style="margin:6px;">
    <el-tabs tab-position="left" style="padding:50px;" class="product-tabs" v-model="activeTab" @tab-click="goBack">
      <el-tab-pane name="basic">
        <template #label>
          <span style="color: red;">* </span> 基本信息
        </template>
        <el-form style="padding-left:20px;" ref="productFormRef" :inline="true" :model="form" :rules="rules"
          label-width="auto">
          <el-row :gutter="100">
            <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="8">
              <el-form-item label="产品分类" prop="categoryId">
                <el-select v-model="form.categoryId" placeholder="请选择分类" @change="selectCategory"
                  :disabled="form.status == 2">
                  <el-option v-for="category in categoryShortArray" :key="category.categoryId"
                    :label="category.categoryName" :value="category.categoryId"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="产品名称" prop="productName">
                <el-input v-model="form.productName" placeholder="请输入产品名称" />
              </el-form-item>
              <el-form-item label="设备类型" prop="deviceType">
                <el-select v-model="form.deviceType" placeholder="请选择设备类型">
                  <el-option v-for="dict in iot_device_type" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="传输协议" prop="transport">
                <el-select v-model="form.transport" placeholder="请选择传输协议">
                  <el-option v-for="dict in iot_transport" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item v-if="form.deviceType !== 3" label="编码协议" prop="protocolCode">
                <el-select v-model="form.protocolCode" placeholder="请选择编码协议">
                  <el-option v-for="dict in iot_protocol_code" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="联网方式" prop="networkMethod">
                <el-select v-model="form.networkMethod" placeholder="请选择联网方式">
                  <el-option v-for="dict in iot_network_method" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="备注信息" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" :rows=3 />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="24" :md="24" :lg="12" :xl="8">
              <el-form-item label="启用授权" prop="isAuthorize">
                <el-switch v-model="form.isAuthorize" active-value="1" inactive-value="0" />
              </el-form-item>
              <el-form-item label="认证方式" prop="vertificateMethod" style="width:100%">
                <el-select v-model="form.vertificateMethod" placeholder="请选择认证方式">
                  <el-option v-for="dict in iot_vertificate_method" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="设备编号" prop="deviceId">
                <el-input placeholder="请输入设备编号" model-value="0" disabled />
              </el-form-item>
              <el-form-item label="mqtt账号" prop="mqttAccount">
                <el-input v-model="form.mqttAccount" placeholder="请输入mqtt账号" />
              </el-form-item>
              <el-form-item label="mqtt密码" prop="mqttPassword">
                <el-input v-model="form.mqttPassword" placeholder="请输入mqtt密码" />
              </el-form-item>
              <el-form-item label="产品秘钥" prop="mqttSecret">
                <el-input v-model="form.mqttSecret" placeholder="请输入产品秘钥" />
              </el-form-item>
              <el-form-item label="产品图片" prop="imgUrl">
                <image-upload v-model="form.imgUrl" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-col :span="20" style="text-align: center;">
            <el-form-item style="margin:40px 0px;">
              <el-button :loading="buttonLoading" type="primary" @click="submitForm" v-hasPermi="['iot:product:edit']"
                v-show="form.productId != undefined && form.status != 2">修 改</el-button>
              <el-button :loading="buttonLoading" type="primary" @click="submitForm" v-hasPermi="['iot:product:add']"
                v-show="form.productId == undefined && form.status != 2">新 增</el-button>
            </el-form-item>
          </el-col>
        </el-form>
      </el-tab-pane>
      <el-tab-pane name="things" :disabled="form.productId == undefined">
        <template #label>
          <span style="color: red;"> * </span>产品模型
        </template>
        <product-things-model :product-id="route.query.productId"></product-things-model>
      </el-tab-pane>
      <el-tab-pane label="设备授权" name="productAuthorize" :disabled="form.productId == undefined">
        <product-authorize></product-authorize>
      </el-tab-pane>
      <!-- 用于设置间距 -->
      <el-tab-pane disabled style="padding-top:200px;">
        <span slot="label">
          <div></div>
        </span>
      </el-tab-pane>
      <el-tab-pane name="product04" v-if="form.status == 1" label="发布产品">
        <template #label>
          <span class="custom-tabs-label">
            <el-button type="danger" size="small">发布产品</el-button>
          </span>
        </template>
      </el-tab-pane>
      <el-tab-pane name="product05" v-if="form.status == 2" label="取消发布">

      </el-tab-pane>
      <el-tab-pane name="product06" label="返回列表">
        <template #label>
          <span class="custom-tabs-label">
            <el-button type="info" size="small">返回列表</el-button>
          </span>
        </template>
      </el-tab-pane>
    </el-tabs>
  </el-card>
</template>
<script setup name="product-edit" lang="ts">
import type { RouteLocationNormalized } from 'vue-router';
import type { TabsPaneContext } from 'element-plus'
import { ProductVO, ProductQuery, ProductForm, CategoryShortList, CategoryShort } from '@/api/iot/product/types';
import { listProduct, getProduct, delProduct, addProduct, updateProduct, selectCategoryShortList } from '@/api/iot/product';
import productThingsModel from './product-things-model.vue'
import productAuthorize from './product-authorize.vue';
const loading = ref(true);
const productFormRef = ref<ElFormInstance>();
const buttonLoading = ref(false);
const route = useRoute();
const productIdAdd = ref('');
const productNameAdd = ref('');

const productIdModel = ref('');

provide('productIdAdd', productIdAdd);
provide('productNameAdd', productNameAdd);
onMounted(() => {
  loadCategoryData();
  //监听路由参数变化
  // console.log("路由参数:", route.query.productId);
  // const productId = Array.isArray(route.query.productId)
  //   ? route.query.productId[0]
  //   : route.query.productId;

  console.log("路由参数:", route.query.productId);
  if (route.query.productId) {
    getProductInfo();
  }

});

const getProductInfo = async () => {
  console.log("getProductInfo");
  loading.value = true;
  const productId = Array.isArray(route.query.productId)
    ? route.query.productId[0]
    : route.query.productId;
  console.log("productId:", productId);
  const res = await getProduct(productId);
  const productData = res.data;
  console.log("productIdAdd:", productData.productId);
  productIdAdd.value = productData.productId as string;
  console.log("productIdAdd:", productIdAdd.value);
  console.log("Number:", Number.MAX_VALUE);
  productNameAdd.value = productData.productName;
  // productIdModel.value = productIdModel ;
  Object.assign(form.value, productData);
  loading.value = false;
}


const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { iot_vertificate_method, iot_device_type, iot_transport, iot_network_method, iot_protocol_code } = toRefs<any>(proxy?.useDict('iot_vertificate_method', 'iot_device_type', 'iot_transport', 'iot_network_method', 'iot_protocol_code'));

// 设置默认激活的标签页为 basic
const activeTab = ref('basic')
const initFormData: ProductForm = {
  productId: undefined,
  productName: undefined,
  protocolCode: undefined,
  categoryId: undefined,
  categoryName: undefined,
  isSys: undefined,
  isAuthorize: undefined,
  mqttAccount: undefined,
  mqttPassword: undefined,
  mqttSecret: undefined,
  status: undefined,
  thingsModelsJson: undefined,
  deviceType: undefined,
  networkMethod: undefined,
  vertificateMethod: undefined,
  transport: undefined,
  imgUrl: undefined,
  remark: undefined
}
const data = reactive<PageData<ProductForm, ProductQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productName: undefined,
    categoryName: undefined,
    status: undefined,
    params: {
    }
  },
  rules: {
    productId: [
      { required: true, message: "产品ID不能为空", trigger: "blur" }
    ],
    productName: [
      { required: true, message: "产品名称不能为空", trigger: "blur" }
    ],
    categoryId: [
      { required: true, message: "产品分类ID不能为空", trigger: "change" }
    ],
    categoryName: [
      { required: true, message: "产品分类名称不能为空", trigger: "change" }
    ],
    deviceType: [
      { required: true, message: "设备类型", trigger: "change" }
    ],
    transport: [
      { required: true, message: "传输协议", trigger: "change" }
    ],
    protocolCode: [
      { required: true, message: "编码协议", trigger: "change" }
    ]
  }
});
const { form, rules } = toRefs(data);
const categoryShortArray = ref<CategoryShort[]>([]);

// 获取分类列表
const loadCategoryData = async () => {
  try {
    const res = await selectCategoryShortList();
    categoryShortArray.value = res.data.map(item => ({
      categoryId: item.categoryId,
      categoryName: item.categoryName
    }));
  } catch (error) {
    console.error("获取分类列表失败:", error);
  }
};
/** 提交按钮 */
const submitForm = () => {
  productFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.productId) {
        await updateProduct(form.value).finally(() => buttonLoading.value = false);
      } else {
        await addProduct(form.value).then((res) =>
          form.value = res.data
        )
          .finally(() => buttonLoading.value = false);
      }
      proxy?.$modal.msgSuccess("操作成功");
    }
  });
}
/** 选择分类 */
const selectCategory = (val) => {
  for (var i = 0; i < categoryShortArray.value.length; i++) {
    if (categoryShortArray.value[i].categoryId == val) {
      form.value.categoryName = categoryShortArray.value[i].categoryName;
      return;
    }
  }
}
/**返回列表并刷新 */
const goBack = (tab: TabsPaneContext, event: Event) => {
  console.log(tab.paneName);
  if (tab.paneName == "product06") {
    proxy?.$tab.closePage();
    // 刷新指定页签
    const obj = { path: "/device/product", name: "product" };
    proxy?.$tab.refreshPage(obj as RouteLocationNormalized);
  }
  if (tab.paneName == "product04") {
    alert("取消发布成功");
  }

}






</script>

<style></style>